package com.gitee.wsl.android.ext.device

import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.Context
import android.os.Build
import android.os.PowerManager
import android.os.PowerManager.WakeLock
import android.provider.Settings
import android.view.Window
import android.view.WindowManager
import com.gitee.wsl.android.ext.ApplicationInit.application
import timber.log.Timber


object BrightnessExt{
    // 电源管理锁
    private val mWakeLock: WakeLock = globalPowerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.FULL_WAKE_LOCK, BrightnessExt::class.java.simpleName)

    /**
     * 屏幕是否打开 ( 亮屏 )
     * @return `true` yes, `false` no
     */
    fun isScreenOn(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            globalPowerManager.isInteractive
        } else globalPowerManager.isScreenOn()
    }

    /**
     * 唤醒 / 点亮 屏幕
     * @return `true` success, `false` fail
     */
    @SuppressLint("WakelockTimeout")
    fun turnScreenOn(): Boolean {
        if (!mWakeLock.isHeld) {
            try {
                mWakeLock.acquire()
                return true
            } catch (e: Exception) {
                Timber.d( e, "turnScreenOn")
            }
        }
        return false
    }

    /**
     * 释放屏幕锁 ( 允许休眠时间自动黑屏 )
     * @return `true` success, `false` fail
     */
    fun turnScreenOff(): Boolean {
        if (mWakeLock.isHeld) {
            try {
                mWakeLock.release()
                return true
            } catch (e: Exception) {
                Timber.d( e, "turnScreenOff")
            }
        }
        return false
    }

    /**
     * 设置 WakeLock 常亮
     * <pre>
     * Activity#onResume() 调用 setWakeLockToBright()
     * Activity#onPause() 调用 mWakeLock.release()
    </pre> *
     * @return [PowerManager.WakeLock]
     */
    @SuppressLint("WakelockTimeout")
    fun setWakeLockToBright(): WakeLock? {
        try {
            // onResume()
            //val mWakeLock: WakeLock = application.powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK or PowerManager.ON_AFTER_RELEASE, TAG)
            mWakeLock.acquire() // 常量, 持有不黑屏

//        // onPause()
//        if (mWakeLock != null) {
//            mWakeLock.release(); // 释放资源, 到休眠时间自动黑屏
//        }
            return mWakeLock
        } catch (e: java.lang.Exception) {
            Timber.d( e, "setWakeLockToBright")
        }
        return null
    }

    /**
     * 设置进入休眠时长
     * @param duration 时长
     * @return `true` success, `false` fail
     */
    fun setSleepDuration(duration: Int): Boolean {
        try {
            Settings.System.putInt(
               application.contentResolver,
                Settings.System.SCREEN_OFF_TIMEOUT,
                duration
            )
            return true
        } catch (e: java.lang.Exception) {
            Timber.d(e, "setSleepDuration")
        }
        return false
    }

    /**
     * 获取进入休眠时长
     * @return 进入休眠时长
     */
    fun getSleepDuration(): Int {
        return try {
            Settings.System.getInt(application.contentResolver, Settings.System.SCREEN_OFF_TIMEOUT)
        } catch (e: java.lang.Exception) {
           Timber.d( e, "getSleepDuration")
            -1
        }
    }

}

val globalPowerManager:PowerManager by lazy { application.powerManager }

val Context.powerManager: PowerManager
    get() = getSystemService(Context.POWER_SERVICE) as PowerManager

/**
 *  automatic brightness mode
 *
 * @return `true`: yes<br></br>`false`: no
 */
inline var autoBrightnessEnabled:Boolean
   get() {
       return try {
           val mode: Int = Settings.System.getInt(
               application.contentResolver,
               Settings.System.SCREEN_BRIGHTNESS_MODE
           )
           mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
       } catch (e: Settings.SettingNotFoundException) {
           e.printStackTrace()
           false
       }
   }
   set(value) {
       Settings.System.putInt(
           application.contentResolver,
           Settings.System.SCREEN_BRIGHTNESS_MODE,
           if (value) Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC else Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
       )
   }


/**
 * 获取屏幕亮度
 *
 * 屏幕亮度 0-255
 */
inline var systemBrightness:Int
     get() {
         return try {
             Settings.System.getInt(
                 application.contentResolver,
                 Settings.System.SCREEN_BRIGHTNESS
             )
         } catch (e: Settings.SettingNotFoundException) {
             e.printStackTrace()
             0
         }
     }
     set(value) {
         val resolver: ContentResolver = application.contentResolver
         Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, value)
         resolver.notifyChange(Settings.System.getUriFor("screen_brightness"), null)
     }

/**
 *
 * 设置窗口亮度
 *
 * */
inline var Window.windowBrightness:Int
    get()  {
       val brightness = attributes.screenBrightness
       return if ( brightness < 0) systemBrightness else ( brightness* 255).toInt()
    }
    set(value) {
            val lp: WindowManager.LayoutParams = attributes
            lp.screenBrightness = value / 255f
            attributes = lp
    }


